package com.gthncz.locks;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * A basic SpinLock
 * <p>
 *     由于每次 getAndSet() 操作都调用 test_and_set 指令,
 *     需要占用 system bus 和 shared memory,
 *     使得 CPU 不能进行对指令进行 reorder,
 *     并且 test_and_set 指令需要使多个 CPU cache coherence.
 *     因此 getAndSet() 操作是十分 heaven 的操作.
 * </p>
 */
public class TASLock implements Lock {

    protected AtomicBoolean state = new AtomicBoolean(false);

    @Override
    public void lock() {
        while(state.getAndSet(true));
    }

    /**
     * 获取 Lock, 除非该线程被中断( interrupted ) .
     * @throws InterruptedException
     */
    @Override
    public void lockInterruptibly() throws InterruptedException {
        throw new UnsupportedOperationException();
    }

    /**
     * 非阻塞式的 lock 方法.
     * 如果没有立即获得锁, 则返回 false.
     * @return
     */
    @Override
    public boolean tryLock() {
        throw new UnsupportedOperationException();
    }

    /**
     * 在 给定时间内获取锁, 并且该线程没有被 interrupted.
     * @param time
     * @param unit
     * @return
     * @throws InterruptedException
     */
    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void unlock() {
        state.set(false);
    }

    @Override
    public Condition newCondition() {
        throw new UnsupportedOperationException();
    }
}

